<?php
namespace SimplePhp\System;

use SimplePhp\Map\NodeReflectionClass;

/**
 *通过反射获取php类
 */
class SpClass implements IClass {
	private static $kernalNamespace = [
		'SimplePhp\Cache',
		'SimplePhp\Database',
		'SimplePhp\Dispatch',
		'SimplePhp\Map',
		'SimplePhp\Rendering',
		'SimplePhp\Section',
		'SimplePhp\System',
		'SimplePhp\Tool',
	];
	/**
	 * 通过反射获取类
	 * @param  [type]  $className   [类名]
	 * @param  string  $namespace   [命名空间:不填就自动加载核心类库]
	 * @param  [type]  $args        [获取实例时的参数]
	 * @param  boolean $getInstanct [是否获取实例]
	 * @return [type]               [返回实例化或者是类的NodeReflectionClass对象]
	 */
	public static function getClass($className, $namespace = "", $getInstanct = false, $args = null) {
		if ($namespace != "") {
			$namespace .= "\\";
		}
		//在核心类库中的话就直接加上类库命名空间
		if ($namespace == "") {
			if ($resultNamespace = SpClass::isKernalFunc($className)) {
				$namespace = $resultNamespace . '\\';
			}
		}
		$class = "\\" . $namespace . $className;
		$ReflectionClass = new NodeReflectionClass($class);
		if (!$getInstanct) {
			return $ReflectionClass;
		}

		if (empty($args)) {
			return $ReflectionClass->newInstance();
		} else {
			return $ReflectionClass->newInstanceArgs($args);
		}
	}
	/**
	 * 检查无指定命名空间的类是否存在于核心库中
	 * @param  [type]  $class [类名]
	 * @return boolean        [命名空间名或者是false 不存在]
	 */
	private static function isKernalFunc($class) {
		foreach (SpClass::$kernalNamespace as $key => $value) {
			if (class_exists("\\" . $value . "\\" . $class)) {
				return $value;
			}
		}
		return false;
	}
}